package com.bwhx.eruler.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bwhx.eruler.bean.Buyer;
import com.bwhx.eruler.bean.BuyerSdk;
import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.service.BuyerSdkService;
import com.bwhx.eruler.service.BuyerService;
import com.bwhx.eruler.util.DateUtils;
import com.bwhx.eruler.util.StringUtils;
/**
 * @author Cuilitang
 *
 */

@Controller
public class BuyerSdkController extends BaseController {
	

	@Autowired
	BuyerService buyerService;
	
	@Autowired
	BuyerSdkService buyerSdkService;
	
	@ResponseBody
	@RequestMapping(value = "/page.buyerSdkList.ashx")
	 public Map<String,Object> buyerSdkList(Integer page,Integer rows,BuyerSdk bs,HttpServletRequest req) {
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,bs);
		Map<String,Object> map = new HashMap<String,Object>();
		Staff s = (Staff)req.getSession().getAttribute("staff");
		if(!s.getsName().equals("admin")){
			bs.setStaffName(s.getsName());
		}
		
		
		try{
			List<BuyerSdk> list = buyerSdkService.list(p);
			Integer count = buyerSdkService.count(bs);
			
			map.put("total",count );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	}
	
	@ResponseBody
	@RequestMapping(value = "/page.saveBuyerSdk.ashx")
	public String saveBuyerSdk(BuyerSdk buyerSdk,HttpServletRequest request) {
		
		
		try{
			if(StringUtils.isEmpty(buyerSdk.getSdkId())){//增加
					
				Staff s = (Staff)request.getSession().getAttribute("staff");
				buyerSdk.setStaffName(s.getsName());
				buyerSdk.setRegisterTime(System.currentTimeMillis()/1000);
			/*	List<BuyerSdk> list1 = buyerSdkService.findByBuerIdAndEndTimeAndType(buyerSdk); //判断sdkId是否有重复
				if(list1.size()!=0){return "alreadyExist";}*/
				
				
				String dateStr = DateUtils.now28String();
				buyerSdk.setDateStr(dateStr);
				String serial = generateSerial(buyerSdk);
				
				
				buyerSdk.setSdkId(serial);
				buyerSdk.setSdkPwd(StringUtils.getRandomString(8));
				buyerSdk.setCounterInt(Integer.parseInt(serial.substring(serial.length()-3, serial.length())));
	
				List<BuyerSdk> list = buyerSdkService.findBySdkId(buyerSdk); //判断sdkId是否有重复
				if(list.size()!=0){return "conflict";}
				
			
				
				buyerSdkService.insert(buyerSdk);
			}else{//修改
				buyerSdkService.update(buyerSdk);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			return "fail";
		}
		
		
	    return "success";  
	  }
	
	
	 
	@ResponseBody
	@RequestMapping(value = "/validateSerialNumber.ashx")
	public Map<String,String> ValidateBuyerSdk(HttpServletRequest request) {
		
		String id = (String)request.getAttribute("id");
		String pwd = (String)request.getAttribute("pwd");
		String devinfo = (String)request.getAttribute("devinfo");
		
		Map<String,String> resultMap = new HashMap<>();
		
		try{		
			
			if(StringUtils.isEmpty(id)||StringUtils.isEmpty(pwd)){
				resultMap.put("status", "0");
				resultMap.put("msg", "参数不全");
				
			}else{
				BuyerSdk buyerSdk  = new BuyerSdk();
				buyerSdk.setSdkId(id);
				buyerSdk.setSdkPwd(pwd);
			
				List<BuyerSdk> list = buyerSdkService.select(buyerSdk);
				
				resultMap.put("nowTime", new Long(System.currentTimeMillis()/1000).toString());

				if(list.size()==0){
					resultMap.put("status", "2");
					resultMap.put("msg", "认证失败,序列号或者密钥错误");
					resultMap.put("why", "1");
					return resultMap;
					
				}else{
					
					BuyerSdk resultBuyerSdk = list.get(0);
					
					resultMap.put("endTime", resultBuyerSdk.getEndTime().toString());
					
					if(resultBuyerSdk.getEndTime()<System.currentTimeMillis()/1000){
						resultMap.put(CONSTANT_STATUS, "2");
						resultMap.put(CONSTANT_MSG, "认证失败,序列号过期");
						resultMap.put(CONSTANT_WHY, "2");
						return resultMap;
					}
					
					if(resultBuyerSdk.getClientSUM()!=null&&resultBuyerSdk.getClientSUM()>resultBuyerSdk.getMaxClient()){
						resultMap.put(CONSTANT_STATUS, "2");
						resultMap.put(CONSTANT_MSG, "认证失败,超过最大设备允许数目");
						resultMap.put(CONSTANT_WHY, "3");
						return resultMap;
						
					}
					
					
					
					
					//购买主体企业码
					if(resultBuyerSdk.getBuyerId()!=null){
						
						Buyer buyer = buyerService.get(resultBuyerSdk.getBuyerId());
						resultMap.put("buyercode", buyer.getbCode());
					}else{
						resultMap.put("buyercode", null);
					}
					
					updateDevInfosAndDevCount(id,devinfo);
					resultMap.put(CONSTANT_STATUS, "1");
					resultMap.put(CONSTANT_MSG, "认证成功");
					resultMap.put("clienttype", resultBuyerSdk.getbType().toString());
					
					return resultMap;

				}
			}
		}catch(Exception e){
			log.error(getTrace(e));
			resultMap.put("msg", "失败！系统异常！");
			resultMap.put("status", "0");	
		}
		
		return resultMap;
	  }
	
	private void updateDevInfosAndDevCount(String sdkId, String devinfo) {
		buyerSdkService.updateDevInfosAndDevCount(sdkId,devinfo);
		
	}


	/**
	 * 生成序列号
	 * @return
	 */
	public String generateSerial(BuyerSdk buyerSdk){
		
		String serial = "";
		
		String counter = buyerSdkService.getCouter(buyerSdk);
		String dateStr = buyerSdk.getDateStr();
		
		if(buyerSdk.getbType()==1){
			
			//ESDK20170325001
			serial = "ESDK"+dateStr +counter ;
			

			
			
		}else if(buyerSdk.getbType()==2){
			//EXLS20170325001

			serial = "EFORM"+dateStr+counter;
			
		}else if(buyerSdk.getbType()==3){
			//EBAR20170325001
			serial = "EBAR"+dateStr+counter;
			
		}
		return serial;
		
	}
	
	
	

	

}
